var ws;


function insertPropertyx(query,section) {
    
    var dbx = window.openDatabase("Database", "1.0", "healthavatar", 20000000);
    
    
    dbx.transaction(function (trxn) {
                    trxn.executeSql(query,[],
                                    function (transaction, resultSet) {
                                    console.log('websockt.js >>insert ccr xml file section : '+section );
                                    },
                                    function (transaction, error) {
                                    console.log('websockt.js >>insert ccr xml file fail--------------------------' + section +" : "+ error);
                                    }
                                    );
                    });
    dbx = null;
}


function connect_server() {
    
    console.log("websocket.js >>================================= connect_server() ");
    
	if ("WebSocket" in window) {
        
		var id = sessionStorage.getItem("id");
		ws = new WebSocket("ws://healthavatar.snubi.org:8320");
		
        ws.onopen = function() {            
            console.log("websocket.js >>================================= ## WebSocket ## Connected. ");
			send_message("regist>" + id);
            console.log("websocket.js >>================================= ## WebSocket ## send_message() regist>id " + id);
		};
        
        
		ws.onmessage = function(e) {			
                      
           
            
            console.log("websocket.js <<================================= ## WebSocket ## onmessage() e.data <<<<< " + e.data);            
            var tmp = e.data;
            var ary = tmp.split("@");
            
            if( ary.length > 1)
            {
                console.log("websocket.js <<================================= ## WebSocket ## onmessage() '@' 포함된것  start");
                var aryval = ary[0];
                var query = "";
                
                if( aryval  == "Results")
                {
                    var aryX = ary[1].split("!!");
                    if( aryX.length > 1){
                        //displayloading();
                        console.log("websocket.js <<================================= ## WebSocket ## onmessage() Results genomancer <<<<< " + aryX[1]);
                        CAsignalNewTest(aryX[0],aryX[1],aryX[2],aryX[3]);
                    }else{
                        console.log("websocket.js <<================================= ## WebSocket ## onmessage() Agent_Results ary[1] <<<<< " + ary[1]);
                        query = "insert into Agent_Results  (Description,Type,Testresult_Value,Testresult_Unit) values ('predict blood sugar','기타','"+ary[1]+"' ,'mg/dl')";
                        console.log("websocket.js <<================================= ## WebSocket ## onmessage() insert Agent_Results");
                        insertPropertyx(query,"Agent_Results 1");
                    }
                }
                                    
                if( aryval  == "FunctionalStatus")
                {
                    console.log("websocket.js <<================================= ## WebSocket ## onmessage() Results genomancer <<<<< " + ary[1]);
                    query = "insert into Agent_FunctionalStatus (Description,Type,Testresult_Value,Testresult_Unit) values ('fasting blood sugar','기타','"+ary[1]+"' ,'mg/dl')";
                    console.log("websocket.js <<================================= ## WebSocket ## onmessage() insert Agent_FunctionalStatus");
                    insertPropertyx(query,"Agent_Results 2");
                }
                
                
                if( aryval  == "Twitter")
                {
                    console.log("websocket.js <<================================= ## WebSocket ## onmessage() Twitter <<<<< ");
                    snsCall(ary[1]);
                }
                if( aryval  == "Facebook")
                {
                    console.log("websocket.js <<================================= ## WebSocket ## onmessage() Facebook <<<<< " + ary[2]);
                    snsCall2(ary[2]);
                }

                            
               // console.log("websocket.js <<================================= ## WebSocket ## onmessage() '@' 포함된것 end <<<<< query " + query);
            }
                            
                                                
            if (e.data.indexOf("request") != -1) {
            
                var agent_id, data_type, e_data, ccr_data, req_data;
                e_data      = e.data.replace("request>","").split(":");
                agent_id    = e_data[0];
                data_type   = e_data[1];
                //ccr_data = JSON.parse(localStorage["ccr_json"]);
                //console.log("websocket.js >>## WebSocket ## from server data_type <<<<< "+data_type);
                
                console.log("websocket.js <<================================= ## WebSocket ## onmessage() data_type 13 section  start" + data_type);
                
                if (data_type == "Payers") {
                                req_data = ccr_data.Body.Payers;
                }else if (data_type == "AdvanceDirectives") {
                                req_data = ccr_data.Body.AdvanceDirectives;
                }else if (data_type == "FunctionalStatus") {
                    
                    console.log("websocket.js <<================================= ## WebSocket ## onmessage() functionalstatusToJson()");
                    req_data = functionalstatusToJson();
                    

                }else if (data_type == "LifelogCcr") {
                                req_data = funcToJson();
                                console.log("websocket.js <<================================= ## WebSocket ## onmessage() funcToJson()");
                }else if (data_type == "Problems") {
                                req_data = problemsToJson();
                                console.log("websocket.js <<================================= ## WebSocket ## onmessage() problemsToJson()");
                } else if (data_type == "FamilyHistory") {
                                req_data = ccr_data.Body.FamilyHistory;
                } else if (data_type == "SocialHistory") {
                                req_data = ccr_data.Body.SocialHistory;
                } else if (data_type == "Alerts") {
                                req_data = ccr_data.Body.Alerts;un
                } else if (data_type == "Medications") {
                                req_data = medicationToJson();
                                console.log("websocket.js <<================================= ## WebSocket ## onmessage() medicationToJson()");
                } else if (data_type == "Immunizations") {
                                req_data = ccr_data.Body.Immunizations;
                } else if (data_type == "VitalSigns") {
                                req_data = vitalToJson();
                                console.log("websocket.js <<================================= ## WebSocket ## onmessage() vitalToJson()");
                } else if (data_type == "Results") {
                                req_data = resultsToJson();
                                console.log("websocket.js <<================================= ## WebSocket ## onmessage() resultsToJson()");
                } else if (data_type == "Procedures") {
                                req_data = ccr_data.Body.Procedures;
                } else if (data_type == "Encounters") {
                                req_data = ccr_data.Body.Encounters;
                } else if (!(data_type.indexOf("genomic")==-1)){
                                Warfarin(agent_id,data_type);
                }else{
                                req_data = null;
                }
            
                if (req_data != null)
                {                
                    //req_data = JSON.stringify(req_data);
                    //console.log(req_data);
                    send_message(agent_id + "/" + req_data);
                    console.log("websocket.js >>================================= ## WebSocket ## send_message() agent_id/req_data " + +agent_id + "/" + req_data);                
                }
                else{
                                //console.log("websocket.js >>## WebSocket ## req = null");
                }

            }
                            
            else if(e.data.indexOf("recommend") != -1)
            {
            
            }
                            
        };
                                
                                
        ws.onclose = function() {
                                console.log("websocket.js >>=================================<< ## WebSocket ## onclose()  Connection Closed.");
                                toastr.success('WebSocket Connection Closed!! ReLogin!!');
                                setTimeout("locationHref()",3000);        
        //			alert("Connection Closed. Please Log in again.");
        //			window.location="login.jsp";
        };
                            
    } else {
                                console.log("websocket.js >>## WebSocket ## Your browser doesn't support WebSocket.");
    }
                            
}
                                                
function locationHref(){
                                location.href ="index.html";
}

function send_message(msg) {
                                console.log("websocket.js >>  send_message >> /////////////////////////////////////////////////////////////");
                                ws.send(msg);
                                console.log("websocket.js >>  send_message >> \n\n\n" + msg);
                                console.log("websocket.js >>  send_message >> /////////////////////////////////////////////////////////////");

}
